from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import time
import datetime
import json
import os

class DamaiTicket:
    def __init__(self):
        self.config = self.load_config()
        self.driver = self.init_driver()
        self.wait = WebDriverWait(self.driver, 5)
        
    def load_config(self):
        # 从配置文件加载设置
        # 构建配置文件的完整路径
        config_path = os.path.join(os.path.dirname(__file__), 'config.json')
        with open(config_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    
    def init_driver(self):
        # 初始化浏览器
        options = webdriver.ChromeOptions()
        options.add_argument('--disable-blink-features=AutomationControlled')
        driver = webdriver.Chrome(options=options)
        return driver
    
    def login(self):
        # 打开登录页面
        self.driver.get('https://passport.damai.cn/login')
        print("请在30秒内完成扫码登录")
        time.sleep(60)
        
    def go_to_detail(self):
        # 打开演出详情页
        self.driver.get(self.config['target_url'])
        print("打开演出详情页")
        
    def buy_ticket(self):
        try:
            # 等待购买按钮出现并点击
            buy_btn = self.wait.until(
                EC.presence_of_element_located((By.CLASS_NAME, "buybtn"))
            )
            buy_btn.click()
            
            # 选择价格
            price = self.wait.until(
                EC.presence_of_element_located((By.XPATH, f"//div[contains(text(), '{self.config['price']}')]"))
            )
            price.click()
            
            # 选择数量
            num = self.wait.until(
                EC.presence_of_element_located((By.CLASS_NAME, "cafe-c-input-number-handler-up"))
            )
            for _ in range(self.config['ticket_num'] - 1):
                num.click()
                
            # 提交订单
            submit = self.wait.until(
                EC.presence_of_element_located((By.CLASS_NAME, "submit-button"))
            )
            submit.click()
            
            # 确认订单
            confirm = self.wait.until(
                EC.presence_of_element_located((By.CLASS_NAME, "submit-wrapper"))
            )
            confirm.click()
            
            print("抢票成功！")
            
        except TimeoutException:
            print("抢票失败，请重试")
            
    def run(self):
        self.login()
        self.go_to_detail()
        
        # 等待到指定时间
        target_time = datetime.datetime.strptime(self.config['buy_time'], '%Y-%m-%d %H:%M:%S')
        while datetime.datetime.now() < target_time:
            time.sleep(0.1)
            
        self.buy_ticket()
        
if __name__ == "__main__":
    ticket = DamaiTicket()
    ticket.run()